package current.aqs;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * 简单实现一个基于AQS并发框架的互斥锁
 */
public class MutexDemo {
    private final Sync sync = new Sync();

    static class Sync extends AbstractQueuedSynchronizer {
        @Override
        protected boolean tryAcquire(int arg) {
            return compareAndSetState(0, 1);
        }

        @Override
        protected boolean tryRelease(int arg) {
            return compareAndSetState(1, 0);
        }
    }

    /**
     * 加锁
     */
    public void lock() {
        sync.acquire(0);
    }

    /**
     * 解锁
     */
    public void unlock() {
        sync.release(0);
    }

    // 临界资源
    public static int i = 0;

    public static void main(String[] args) throws InterruptedException {
        MutexDemo mutex = new MutexDemo();

        Thread t1 = new Thread(() -> {
            mutex.lock();
            for (int j = 0; j < 10000; j++) {
                i++;
            }
            mutex.unlock();
        });
        t1.start();

        Thread t2 = new Thread(() -> {
            mutex.lock();
            for (int j = 0; j < 10000; j++) {
                i++;
            }
            mutex.unlock();
        });
        t2.start();

        t1.join();
        t2.join();

        System.out.println(i);
    }
}
